/*
 * @Author: 89-83-77
 * @Description: 请填写当前文件简介
 * @Date: 2025-03-27 23:55:01
 * @LastEditTime: 2025-03-28 00:11:46
 * @FilePath: \event-analysis-systemd:\Desktop\client\src\stores\menu.js
 */
import { defineStore } from "pinia";

export const useMenuStore = defineStore("menu", {
  state: () => ({
    menus: [
      {
        path: "/dashboard",
        meta: {
          title: "数据概览",
          icon: "PieChart",
          order: 1,
          permissions: ["admin"],
        },
      },
      {
        path: "/system",
        meta: {
          title: "系统管理",
          icon: "Setting",
          order: 2,
          permissions: ["admin"],
        },
        children: [
          {
            path: "menu",
            meta: {
              title: "菜单管理",
              icon: "Menu",
              order: 1,
              permissions: ["admin"],
            },
          },
          {
            path: "role",
            meta: {
              title: "角色管理",
              icon: "UserFilled",
              order: 2,
              permissions: ["admin"],
            },
          },
        ],
      },
    ],
  }),
  getters: {
    sortedMenus: (state) => {
      const sortByOrder = (a, b) => a.meta.order - b.meta.order;
      const deepSort = (menus) => {
        return [...menus].sort(sortByOrder).map((menu) => ({
          ...menu,
          children: menu.children ? deepSort(menu.children) : [],
        }));
      };
      return deepSort(state.menus);
    },
  },
  actions: {
    async updateMenu(menu) {
      const findAndUpdate = (menus) => {
        return menus.map((m) => {
          if (m.path === menu.path) return menu;
          if (m.children) {
            return {
              ...m,
              children: findAndUpdate(m.children),
            };
          }
          return m;
        });
      };
      this.menus = findAndUpdate(this.menus);
    },
    async deleteMenu(path) {
      const removeFromTree = (menus) => {
        return menus
          .filter((m) => m.path !== path)
          .map((m) => {
            if (m.children) {
              return {
                ...m,
                children: removeFromTree(m.children),
              };
            }
            return m;
          });
      };
      this.menus = removeFromTree(this.menus);
    },
  },
});
